package com.shuchengrj.common.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author haoakongzi
 */
@Slf4j
public class HttpUtils {


    public static String doGet(String url) {
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        try {
            httpClient = getHttpClient();
            HttpGet request = new HttpGet(url);
            response = httpClient.execute(request);
            /** 请求发送成功，并得到响应 **/
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                /** 读取服务器返回过来的json字符串数据 **/
                String strResult = EntityUtils.toString(response.getEntity());
                return strResult;
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            closeHttpResponse(response);
            closeHttpClient(httpClient);
        }
        return null;
    }

    /**
     * post请求(用于key-value格式的参数)
     *
     * @param url
     * @param params
     * @return
     */
    public static String doPost(String url, Map<String, Object> params) {
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        try {
            httpClient = getHttpClient();
            // 实例化HTTP方法
            HttpPost request = new HttpPost(url);
            List<NameValuePair> nvps = new ArrayList<NameValuePair>();
            params.forEach((key, value) -> {
                nvps.add(new BasicNameValuePair(key, String.valueOf(value)));
            });
            request.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
            response = httpClient.execute(request);
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == HttpStatus.SC_OK) {
                return EntityUtils.toString(response.getEntity());
            } else {
                log.error("postRequest error, url: {}, errorcode: {}", url, statusCode);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            closeHttpResponse(response);
            closeHttpClient(httpClient);
        }
        return null;
    }

    /**
     * post请求（用于请求json格式的参数）
     *
     * @param url
     * @param params
     * @return
     */
    public static String doPost(String url, String params) {
        {
            CloseableHttpClient httpClient = null;
            BufferedReader in = null;
            CloseableHttpResponse response = null;
            try {
                httpClient = getHttpClient();
                // 实例化HTTP方法
                HttpPost request = new HttpPost(url);

                request.setHeader("Accept", "application/json");
                request.setHeader("Content-Type", "application/json");

                StringEntity entity = new StringEntity(params, "UTF-8");
                request.setEntity(entity);

                response = httpClient.execute(request);
                int statusCode = response.getStatusLine().getStatusCode();
                if (statusCode == HttpStatus.SC_OK) {
                    return EntityUtils.toString(response.getEntity());
                } else {
                    log.error("postRequest error, url: {}, errorcode: {}", url, statusCode);
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                closeHttpResponse(response);
                closeHttpClient(httpClient);
            }
            return null;
        }
    }

    private static void closeHttpClient(CloseableHttpClient httpClient) {
        if (httpClient != null) {
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private static void closeHttpResponse(CloseableHttpResponse httpResponse) {
        if (httpResponse != null) {
            try {
                httpResponse.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private static CloseableHttpClient getHttpClient() {
        return HttpClientBuilder.create().build();
    }

}
